/*
 * File Name :  DropDownWidget.js
 */
import { getOpt } from '../tools.js';
import Mn from 'backbone.marionette';
import ButtonWidget from './ButtonWidget.js';
import IconWidget from './IconWidget.js';
import ButtonCollection from '../base/models/ButtonCollection.js';

const DropDownItemsView = Mn.CollectionView.extend({
    tagName: 'ul',
    className: function(){
        let result = 'dropdown-menu';
        let orientation = getOpt(this, 'orientation', 'right');
        result += ' dropdown-menu-' + orientation;
        return result;
    },
    childView: ButtonWidget,
    // On forward l'évènement action:clicked
    childViewTriggers: {
        'action:clicked': 'action:clicked'
    },
    childViewOptions: {
        surroundingTagName: 'li',
        css: 'unstyled'
    },
});

const DropDownWidget = Mn.View.extend({
    /*
     * A dropdown composite view
     * shows a dropdown with a main button
     *
     * :param str dropDownLabel: The label (used for screen readers in case of showLabel is false)
     * :param str showLabel: default false (should we show the label in any case)
     * :param str icon: The icon
     * :param str css: The css
     * :param obj collection: ButtonCollection
     * :param str orientation: dropdown right/left orientation regarding the need
     *
     * a dropdown button
     * a dropdown populated with the provided collection
     *
     * Triggers action:clicked with param 'action'
     */
    default_icon: "dots",
    tatgName: "div",
    className: "btn-group",
    attributes:{
        style: "display:inline-flex"
    },
    template: require('./templates/DropDownWidget.mustache'),
    regions: {
        list: {
            el: 'ul',
            replaceElement: true
        },
        icon: {
            el: 'icon',
            replaceElement: true
        }
    },
    // On forward l'évènement action:clicked
    childViewTriggers: {
        'action:clicked': 'action:clicked'
    },
    initialize(options){
        if (!('collection' in options)) {
            this.collection = new ButtonCollection(options.buttons);
        }
    },
    onRender(){
        this.showChildView(
            'list',
            new DropDownItemsView({collection: this.collection, orientation: getOpt(this, 'orientation', 'right')})
        );
        this.showChildView(
            'icon',
            new IconWidget({icon: getOpt(this, 'icon', this.default_icon)})
        );
    },
    templateContext(){
        return {
            label: this.getOption('dropdownLabel'),
            showLabel: getOpt(this, 'showLabel', false),
            css: getOpt(this, "css", ''),
            orientation: getOpt(this, 'orientation', 'left'),
        }
    }
});
export default DropDownWidget;
